<template>
    <div class="app-container">
        <el-card>
            <div class="fs18 fwb mb20">积分数据</div>
            <div class="flex flex ver flex-sb mb40">
                <div>
                    <!-- <el-cascader ref="cascader" :props="waterMachineProps" v-model="waterMachineData"
                        :options="waterMachineOptions" @change="handleChange" @expand-change="expandChange"
                        placeholder="请选择一台水机，以查看数据" class="w300"></el-cascader> -->

                    <el-select v-model="waterMachineData" placeholder="请选择用户" size="small" class="mr-10" @change="handleChange">
                        <el-option v-for="(item, index) in userList" :key="index" :label="item.nickname"
                            :value="item.id"></el-option>
                    </el-select>

                </div>

                <div class="flex flex-ver">
                    <div class="flex">
                        <div :class="['opt-btn', { active: type == 'day' }]" @click="changeTime('day')">按天</div>
                        <div :class="['opt-btn', { active: type == 'month' }]" @click="changeTime('month')">按月</div>
                        <div :class="['opt-btn', { active: type == 'year' }]" @click="changeTime('year')">按年</div>
                    </div>

                    <div v-show="type == 'day'">
                        <el-date-picker v-model="dateData" type="daterange" @change="dateDataChange"
                            range-separator="至" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期">
                        </el-date-picker>
                    </div>

                    <div v-show="type == 'month'">
                        <el-date-picker v-model="monthData" type="monthrange" @change="monthDataChange"
                            range-separator="至" value-format="yyyy-MM" start-placeholder="开始月份" end-placeholder="结束月份">
                        </el-date-picker>
                    </div>

                    <div v-show="type == 'year'">
                        <el-date-picker v-model="yearsStart" :picker-options="startDatePicker" value-format="yyyy"
                            type="year" placeholder="开始年份" @change="changeStartYear">
                        </el-date-picker>
                        ~
                        <el-date-picker v-model="yearsEnd" value-format="yyyy" @change="changeEndYear"
                            :picker-options="endDatePicker" type="year" placeholder="结束年份">
                        </el-date-picker>
                    </div>
                </div>
            </div>


            <div class="empty-machine flex flex-center fs22" v-show="$common._empty(waterMachineData)">请选择用户，以查看数据</div>

            <!-- 图标 -->
            <div id="columnChart" v-show="!$common._empty(waterMachineData)"></div>



            <!-- 列表 -->
            <!-- <Table :rolesList="rolesList" :marginTop="10">
            <el-table-column align="center" label="序号">
                <template slot-scope="scope">{{ scope.row.id }}</template>
</el-table-column>
<el-table-column align="center" label="水机编号">
    <template slot-scope="scope">{{ scope.row.code }}</template>
</el-table-column>
<el-table-column align="center" label="创建时间">
    <template slot-scope="scope">{{ scope.row.created_at }}</template>
</el-table-column>

<el-table-column align="center" label="操作">
    <template slot-scope="scope">
                    <router-link class :to="{
                    name: 'waterDetail',
                    params: { id: scope.row.id },
                }">
                        <el-button type="primary" class="add-button mr-10" size="mini">查看</el-button>
                    </router-link>


                    <el-dropdown @command="handleCommand($event, scope.row)">
                        <el-button type="danger" class="operation-button">
                            更多<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="modify">编辑</el-dropdown-item>
                            <el-dropdown-item command="del">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>

                </template>
</el-table-column>
</Table> -->

            <!-- 分页 -->
            <!-- <Pagination style="margin-top: 10px" :pageSize="pgSize" :totalCount="ttCount" :currentPage="currentPageNumber"
            @pageCurrentChange="pageCurrentChangeEvent"></Pagination> -->
        </el-card>
    </div>
</template>

<script>
import echarts from "echarts";
import Pagination from "@/components/Pagination/index";
import Table from "@/components/table/index";
import {  usersUnusual } from "@/api/grzq/community.js";
import {  statisticsScores } from "@/api/grzq/statistics.js";
export default {
    data() {
        return {
            userList:[],
            startDate: '',
            endDate: '',
            startYearMonth: '',
            endYearMonth: '',
            type: "month",
            startDatePicker: this.beginDate(),
            endDatePicker: this.processDate(),
            yearsStart: '',
            yearsEnd: '',
            monthData: [],
            dateData: [],
            rolesList: [{}, {}],
            pgSize: 0, //默认20 每个20条
            ttCount: 0, //返回总条数
            currentPageNumber: 1, //传递的分页page参数
            waterMachineData: [],
            // waterMachineProps: {
                // value: 'id',
                // label: 'name',
                // emitPath:false, //只返回该节点的值 不返回数组
                // lazy: true,
                // lazyLoad: (node, resolve) => {
                //     const { level } = node;
                //     console.log(node)
                //     if (level == 0) {

                //         getCommunitiesList({ page: 1, page_size: 9999, }).then((res) => {
                //             this.waterMachineOptions = res.data.datas;
                //             resolve(res.data.datas);
                //         })
                //     }
                //     else if(level == 1){
                //     else{
                //         console.log(node.value)
                //         getApparatusList({page: 1,community_id: node.value,page_size: 9999}).then((res) => {
                //            let parentIndex = this.waterMachineOptions.findIndex(i=>i.id == node.value);
                //            this.$set(this.waterMachineOptions[parentIndex],'children',res.data.datas);

                //             resolve(res.data.datas)
                //         });
                //     }
                //     else{
                //         this.$refs.cascader.dropDownVisible = false;
                //     }
                // }
            // },



            // waterMachineOptions: [
                // {name:'a1',id:1},
                // {name:'a2',id:2},
                // {name:'a3',id:3},
            // ],
            communityId: '',//水机id
        }
    },
    computed: {
    },
    watch: {
        yearsStart(newval) {
            if (newval == null) {
                this.$set(this, 'yearsStart', '')
            }
        },
        yearsEnd(newval) {
            if (newval == null) {
                this.$set(this, 'yearsEnd', '')
            }
        },
        dateData: {
            handler: function (newval) {
                if (this.$common._empty(newval)) {
                    this.$set(this, "startDate", "");
                    this.$set(this, "endDate", "");
                } else {
                    this.$set(this, "startDate", newval[0]);
                    this.$set(this, "endDate", newval[1]);
                }
            },
            immediate: true,
            deep: true
        },
        monthData: {
            handler: function (newval) {
                if (this.$common._empty(newval)) {
                    this.$set(this, "startYearMonth", "");
                    this.$set(this, "endYearMonth", "");
                } else {
                    this.$set(this, "startYearMonth", newval[0]);
                    this.$set(this, "endYearMonth", newval[1]);
                }
            },
            immediate: true,
            deep: true
        }
    },
    components: {
        Table,
        Pagination
    },
    async created() {

    },
    async mounted() {
        this.monthData = this.calcCurrentYearMonth();
        await this.usersUnusual(); //改成获取用户列表接口
        await this.columnChart();
    },
    methods: {

        async usersUnusual(){
            const res = await usersUnusual();
            this.userList = res.data;
        },

        async dateDataChange(e) {
            if (this.$common._empty(this.waterMachineData)) {
                this.$message.error('请先选择用户');
                return;
            }

            if(this.$common._empty(e)){
                this.startDate = '';
                this.endDate = '';
            }

            await this.statisticsScores();
        },
        async monthDataChange() {
            if (this.$common._empty(this.waterMachineData)) {
                this.$message.error('请先选择用户');
                return;
            }

            await this.statisticsScores();
        },
        async statisticsScores() {
            const res = await statisticsScores({
                id: this.waterMachineData[1],
                start_time: this.type == 'month' ? this.startYearMonth : this.type == 'day' ? this.startDate :  this.yearsStart ? this.yearsStart + '-01' : '',
                end_time: this.type == 'month' ? this.endYearMonth : this.type == 'day' ? this.endDate :  this.yearsEnd ? this.yearsEnd + '-12' : '',
                type:this.type,
            });
            this.columnChart({
                xAxis: [
                    {
                        data: res.data.date,
                    },
                ],
                series: res.data.series,
            })

        },
        // async expandChange(e, a, c) {
        //     console.log(e);
        //     await this.getApparatusList(e[0]);
        // },
        //获取社区列表
        // async getCommunitiesList() {
        //     const res = await getCommunitiesList(
        //         {
        //             page: this.currentPageNumber,
        //             page_size: 99999
        //         }
        //     );
        //     this.waterMachineOptions = res.data.datas;
        //     this.waterMachineOptions.forEach(i => {
        //         this.$set(i, 'children', []);
        //     })
        // },
        //获取水机列表
        // async getApparatusList(parentId) {
        //     const res = await getApparatusList(
        //         {
        //             page: 1,
        //             community_id: parentId,
        //             page_size: 99999
        //         }
        //     );
        //     let parentIndex = this.waterMachineOptions.findIndex(i => i.id == parentId);
        //     this.$set(this.waterMachineOptions[parentIndex], 'children', res.data.datas);
        // },
        calcCurrentYearMonth() {
            let currentYear = this.$common.getCurrentYear();
            let currentMonth = this.$common.getCurrentMonth();
            let realTime = [];
            if (currentMonth > 0 && currentMonth < 10) {
                if (currentMonth == 9) {
                    realTime = [currentYear + '-0' + currentMonth, currentYear + '-' + Number(currentMonth + 1)];
                } else {
                    realTime = [currentYear + '-0' + currentMonth, currentYear + '-0' + currentMonth];
                }

            } else {
                if (currentMonth == 12) {
                    realTime = [currentYear + '-' + Number(currentMonth, currentYear + 1) + '-01'];
                }

            }
            return realTime;
        },
        getSum() {

        },
        columnChart(newObj) {
            // 基于准备好的dom，初始化echarts实例
            let myChart = echarts.init(document.getElementById("columnChart"));

            // 绘制图表
            let myOption = {
                color: ["#2AAE67", "#F6DE74", '#e4393c', 'blue', 'purple'],
                // toolbox: { //保存 切换折现 柱状
                //     feature: {
                //         // dataView: { show: true, readOnly: false }, //数据视图刷新后有bug 总数显示不对
                //         magicType: { show: true, type: ['line', 'bar'] },
                //         restore: { show: true },
                //         saveAsImage: { show: true }
                //     }
                // },
                tooltip: {
                    trigger: "axis",
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    },
                    formatter: (params,) => {
                        let sumPrice = params.slice(0, 3).reduce((prev, next) => prev + next.value, 0);
                        let sumCount = params.slice(3, 5).reduce((prev, next) => prev + next.value, 0);
                        // console.log(111, params)
                        let s = "";
                        s += `${params[0].axisValue}` + "\n";
                        s +=
                            `共计${parseInt(sumPrice)}积分` + "\n";
                        for (var i = 0; i < params.length; i++) {
                            s += "<div class='flex flex-ver'>";
                            s +=
                                `<div style='margin-right:4px;width:8px;height:8px;background-color:${myOption.color[i]};border-radius:50%'></div>`;
                            s += `<div>${params[i].seriesName}：${params[i].value}积分</div>`;
                            s += "</div>";
                        }

                        return s;
                    },
                    extraCssText: "width:220px; white-space:pre-wrap;", //遮罩层整体样式设置
                },
                legend: {
                },//点击切换暂时隐藏 影响移入的显示数据
                grid: {
                    left: "3%",
                    right: "4%",
                    bottom: "3%",
                    containLabel: true,
                },
                xAxis: [
                    {
                        type: "category",
                        data: [
                            "12-07",
                            "12-08",
                            "12-09",
                            "12-10",
                        ],
                    },
                ],
                yAxis: [
                    {
                        type: "value",
                    },
                ],
                barWidth: 30,
                series: [
                    {
                        name: "微信",
                        type: "bar",
                        stack: "Ad",
                        emphasis: {
                            focus: "series",
                        },
                        // tooltip: { 5.3.0开始支持 目前4.8
                        //     valueFormatter: function (value) {
                        //         return value + '元';
                        //     }
                        // },
                        data: [1, 11, 111, 5],
                    },
                    {
                        name: "注册",
                        type: "bar",
                        stack: "Ad", //此属性控制单排，多排显示
                        emphasis: {
                            focus: "series",
                        },
                        data: [2, 22, 222, 55],
                    },
                    // {
                    //     name: "微信1",
                    //     type: "bar",
                    //     stack: "Ad",
                    //     emphasis: {
                    //         focus: "series",
                    //     },
                    //     data: [3, 33, 333, 555],
                    // },
                    // {
                    //     name: "注册2",
                    //     type: "bar",
                    //     stack: "Ad", //此属性控制单排，多排显示
                    //     emphasis: {
                    //         focus: "series",
                    //     },
                    //     data: [4, 44, 444, 5555],
                    // },
                    // {
                    //     name: "注册3",
                    //     type: "bar",
                    //     stack: "Ad", //此属性控制单排，多排显示
                    //     emphasis: {
                    //         focus: "series",
                    //     },
                    //     data: [5, 55, 5555, 55555],
                    // },
                ],
            };
            Object.assign(myOption, newObj);
            myChart.setOption(myOption);

            // this.$nextTick(()=>{
            myChart.resize();
            // })

        },
        changeTime(type) {
            this.$set(this,'type',type);
            if(!this.$common._empty(this.waterMachineData)) this.statisticsScores();
        },
        async changeStartYear(e){
            if(this.$common._empty(this.yearsEnd)) return;
            if(this.$common._empty(e)) return ;

            await this.statisticsScores();
        },
        async changeEndYear(e) {
            if (this.$common._empty(this.waterMachineData)) {
                this.$message.error('请先选择水机');
                return;
            }
            if(this.$common._empty(this.yearsStart)) return;
            console.log(e);
            if(this.$common._empty(e)) return ;
            //切换第二个picker时调用接口
            await this.statisticsScores();
        },
        async handleChange(value) {
            await this.statisticsScores();
        },

        // 选择年份范围选择时开始时间不能大于结束时间，结束时间不能小于开始时间
        // 提出开始时间必须小于提出结束时间
        beginDate() {
            let self = this
            return {
                disabledDate(time) {
                    if (self.yearsEnd !== '') {
                        let fixedTime = new Date(time)
                        return fixedTime.getFullYear() > self.yearsEnd
                    }
                }
            }
        },
        // 提出结束时间必须大于提出开始时间
        processDate() {
            let self = this
            return {
                disabledDate(time) {
                    // let fixedTime = new Date(self.oldTime).getTime()
                    // return time.getTime() < fixedTime
                    let fixedTime = new Date(time)
                    return fixedTime.getFullYear() < self.yearsStart
                }
            }
        },

        //分页change事件
        pageCurrentChangeEvent(e) {
            // this.currentPageNumber = e;
            // this.$router.push({
            //     query: Object.assign(this.dataForm, { page: e }),
            // });





            // this.getData();//getData
        },
    },
    destroyed() {
    }
}
</script>

<style scoped lang="scss">
.opt-btn {
    width: 60px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 12px;
    border: 1px solid rgb(220, 223, 230);
    cursor: pointer;
}

#columnChart {
    width: 100%;
    height: 400px;
}

.empty-machine {
    width: 100%;
    height: 400px;
}

.active {
    border-color: #409EFF;
    color: #409EFF;
}
</style>
